package com.aizuda.easyManagerTool.service.setting.impl.alarm;

import cn.hutool.core.util.ObjectUtil;
import com.aizuda.easyManagerTool.domain.dto.setting.SettingAlarmTestDTO;
import com.aizuda.easyManagerTool.domain.entity.setting.SettingAlarmEntity;
import com.aizuda.easyManagerTool.mapper.setting.SettingAlarmMapper;
import com.aizuda.easyManagerTool.util.AssertUtil;
import com.aizuda.easyManagerTool.util.ThreadPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class AlarmStrategy {

    @Resource
    private SettingAlarmMapper settingAlarmMapper;
    private ThreadPoolUtil executorService = new ThreadPoolUtil("监控数据告警-");

    private Map<String,AlarmService> alarmServiceMap = new ConcurrentHashMap<String,AlarmService>();

    @Autowired
    public AlarmStrategy(Map<String,AlarmService> alarmServiceMap){
        this.alarmServiceMap = alarmServiceMap;
    }

    public void send(String title,String text,Integer tenantId){
        executorService.execute(() -> {
            SettingAlarmEntity settingAlarmEntity = settingAlarmMapper.findByTenantId(tenantId);
            if(ObjectUtil.isEmpty(settingAlarmEntity)){
                return;
            }
            alarmServiceMap.values().forEach(item -> {
                try {
                    item.send(title,text,settingAlarmEntity);
                } catch (Exception e) {
                    log.error("业务 {}, 发送失败 {}",item.getClass(),e.getMessage());
                }
            });
        });
    }

    public void send(String title, String text, SettingAlarmTestDTO settingAlarmTestDTO){
        AlarmService alarmService = alarmServiceMap.get(settingAlarmTestDTO.getTag());
        AssertUtil.objIsNull(alarmService, "服务找不到");
        alarmService.send(title,text,settingAlarmTestDTO);
    }

}
